package com.bridgeintelligent.tag.webserver.dim.mgmt.service.scheduled;

import com.bridgeintelligent.tag.mapper.DepartmentMapper;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DepartmentRep;
import com.bridgeintelligent.tag.webserver.dim.mgmt.api.DimDepartment;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by JackCheung on 2019/9/27 6:28 PM.
 */
@Slf4j
@AllArgsConstructor
@Service
public class DepartmentScheduledService {

    private SqlSessionTemplate sqlSessionTemplate;

    public void updateDepartment(DepartmentRep departmentRep) {
        List<DimDepartment> list = departmentRep.getData().getOrg().stream().map(org -> new DimDepartment(org.getCode(), org.getDisplayName(), "0")).collect(Collectors.toList());
        SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);
        DepartmentMapper departmentMapperBatch = sqlSession.getMapper(DepartmentMapper.class);
        departmentMapperBatch.del();
        list.forEach(departmentMapperBatch::insert);
        try {
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("同步部门出现异常……{}", e.getMessage());
        } finally {
            sqlSession.close();
        }
    }
}
